import axios from "axios";
import { useEffect, useState } from "react";
import { SidebarStaff } from "./Sidebar";
import { useParams } from "react-router-dom";
import { AddTAappointment, RemoveTAappointment } from "../actions/UserActions";

const PopUp = props => {
  return (
    <div className="popup-box">
      <div className="box">
        <span
          className="close-icon"
          onClick={props.handleClose}
        >x
        </span>
        {props.content}
      </div>
    </div>
  )
}

export const AppointTA = () => {
  const params = useParams();
  const [saRoleCheck, setSaRoleCheck] = useState(false);
  const [moduleInfo, setModuleInfo] = useState("");
  const [addTAPopUp, setAddTAPopUp] = useState(false);
  const [removeTAPopUp, setRemoveTAPopUp] = useState(false);
  const [tasInfo, setTAsInfo] = useState([]);
  const [newTAs, setNewTAs] = useState("");
  const [taRemoved, setTARemoved] = useState("");

  //check if staff is already logged in
  useEffect(() => {
    axios({
      method: 'GET',
      headers: { "satoken": window.localStorage.getItem("satoken") },
      url: 'http://localhost:8080/user/staff/module',
    })
      .then((res) => {
        if (res.data.success) {
          setSaRoleCheck(true);
        }
        else { setSaRoleCheck(false); }
      });
  }, []); // initial render

  // get module info to display
  useEffect(() => {
    axios({
      method: 'GET',
      headers: { "satoken": window.localStorage.getItem("satoken") },
      url: 'http://localhost:8080/module/info/' + params.id,
    })
      .then((res) => {
        if (res.data.success) {
          setModuleInfo(res.data['data']['code'] + ' ' + res.data['data']['name']);
        }
      });
  }, [params.id]); // initial render

  // get TAs appointed in this module
  useEffect(() => {
    axios({
      method: 'GET',
      headers: { "satoken": window.localStorage.getItem("satoken") },
      url: 'http://localhost:8080/supervision/module/' + params.id,
    })
      .then((res) => {
        if (res.data.success) {
          setTAsInfo(res.data['data']);
        }
      });
  }, [params.id]); // initial render

  // toggle appoint TA pop up form
  const toggleAddTAPopUp = () => {
    setAddTAPopUp(!addTAPopUp);
  }

  // toggle confirmation pop up before removing TA
  const toggleRemoveTAPopUp = () => {
    setRemoveTAPopUp(!removeTAPopUp);
  }

  // submit new appointment
  const handleSubmitAppointment = () => {
    if (newTAs === "") {
      alert("At least one TA email required!");
      return;
    }
    let tasList = newTAs.split(/[;,' ']+/);
    tasList.forEach((s) => {
      // appoint new TAs in this module_id
      AddTAappointment(params.id, s, 1);
    })
  }

  // remove TA from appointment
  const handleRemoveTA = () => {
    RemoveTAappointment(params.id, taRemoved);
  }


  if (saRoleCheck) {
    return (
      <>
        <SidebarStaff />
        <div className="moduleCard">
          <h3>{moduleInfo}</h3>
          <p>Teaching Assistants Appointed:</p>
          <table id="student-table">
            <thead>
              <tr>
                <th>Email</th>
                <th>Name</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {tasInfo.map((item) => {
                return (
                  <tr key={item.id}>
                    <td>{item.email}</td>
                    <td>{item.name}</td>
                    <td>
                      <button
                        id="remove-student-table"
                        onClick={() => {
                          setTARemoved(item.email);
                          toggleRemoveTAPopUp();
                        }}
                      >Remove
                      </button>
                    </td>
                  </tr>
                )
              })}
            </tbody>
          </table>

          <button
            id="addStudent"
            onClick={toggleAddTAPopUp}
          >+ Add TAs
          </button>

          {addTAPopUp && <PopUp
            content={
              <>
                <label htmlFor="newTAs">
                  Enter TA emails separated by either space, comma or semicolon:
                </label><br></br>

                <input
                  id="inputAddStudent"
                  value={newTAs}
                  onChange={(e) => setNewTAs(e.target.value)}
                  placeholder="eg: ta1@u.nus.edu; ta2@u.nus.edu"
                /><br></br>

                <button className="Button" onClick={handleSubmitAppointment}>
                  Appoint TAs
                </button>
              </>}
            handleClose={toggleAddTAPopUp}
          />}

          {removeTAPopUp && <PopUp
            content={
              <>
                <p>Are you sure you want to remove this TA from the module?</p>
                <b>{taRemoved}</b>
                <div>
                  <button
                    className="Button"
                    style={{ backgroundColor: "#fa4549" }}
                    onClick={handleRemoveTA}
                  >Remove TA
                  </button>
                </div>
              </>}
            handleClose={toggleRemoveTAPopUp}
          />}

        </div>
      </>
    )
  }
  else {
    return (
      <></>
    )
  }

}